import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Item } from '@/assets/type/commonType'
import { dymRouterNames } from '@/router/routerNames'
import type {Router} from 'vue-router'

export const userLoginStore = defineStore('userLogin', () => {
  const token = ref<string>('')
  const menuList = ref<Item[]>([])
  const routerList = ref([])

  const updateMenuList = function (val: Item[]){
    menuList.value = val
  }

  const addRouter = function (router: Router){
    const menu = menuList.value
    routerList.value = []
    const module = import.meta.glob('../views/**/*.vue')
    const routes = []
    menu.forEach(item => {
      if (item.children){
        (item.children as Item[]).forEach(val => {
          const url = `../views/${val.url}.vue`
          val.component = module[url]
          routes.push(...item.children)
        })
      } else {
        const url = `../views/${item.url}.vue`
        item.component = module[url]
        routes.push(item)
      }
    })
    const routers = router.getRoutes()
    routers.forEach(item => {
      if (!dymRouterNames.includes(item.name as string) && item.name){
        router.removeRoute(item.name as string)
      }
    })
    routes.forEach(item => {
      routerList.value.push(router.addRoute('main', item))
    })
  }
  return {
    token,
    menuList,
    routerList,
    updateMenuList,
    addRouter
  }
})
